package com.app.shop.fragments;


import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.shop.R;
import com.app.shop.activitys.GoodsDetailActivity;
import com.app.shop.activitys.SearchActivity;
import com.app.shop.adapters.GoodsListAdapter;
import com.app.shop.adapters.TiaoSaoListAdapter;
import com.app.shop.beans.GoodsBean;
import com.app.library.base.BaseFragment;
import com.app.library.beans.EventMessage;
import com.app.library.utils.DialogUtil;
import com.app.library.utils.GlideUtils;
import com.app.library.utils.ToastUtil;
import com.app.library.widgts.CustomDialog;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends BaseFragment {

    @BindView(R.id.recy)
    RecyclerView recy;

    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.recy_tiaosao)
    RecyclerView recyTiaosao;

    private List<GoodsBean> list = new ArrayList<>();
    private GoodsListAdapter adapter;


    private String dialog_title = "删除该商品";
    private String dialog_content = "是否确定操作？";
    private CustomDialog customDialog;
    public static HomeFragment getInstance(){
        HomeFragment fragment=new HomeFragment();
        return fragment;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        recy= (RecyclerView) view.findViewById(R.id.recy);
        banner= (Banner)view. findViewById(R.id.banner);
        recyTiaosao= (RecyclerView) view.findViewById(R.id.recy_tiaosao);

      TextView  tvsearch= (TextView) view.findViewById(R.id.tv_search);
        tvsearch.setOnClickListener(this::onViewClicked);
        registerEventBus();
        recy.setFocusable(false);
        recy.setFocusableInTouchMode(false);
        initBanner();
        initTiaoSao();
        initList();
        return view;
    }

    private void initTiaoSao() {
        recyTiaosao.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        List<String> list = new ArrayList<>();
        list.add("http://a1.qpic.cn/psc?/V54eSsR74GmfBT42pSAT26RsMd0ZtmmF/bqQfVz5yrrGYSXMvKr.cqWUDf6yNIvRGhe.C*s73GLnsaEZK2knx5zQvAFlgxNzHLRyRTAq2E4vMGnJkJs3G61iHyW2XW8rlS.DxOvABUu4!/b&ek=1&kp=1&pt=0&bo=OAQwBDgEMAQDEDU!&tl=1&vuin=972381686&tm=1639357200&sce=50-1-1&rf=viewer_311");
        list.add("http://photogz.photo.store.qq.com/psc?/V54eSsR74GmfBT42pSAT26RsMd0ZtmmF/bqQfVz5yrrGYSXMvKr.cqdhEHhRuBdPZL8vxqM1xtKUyBqw7Nr46N9z7i0bT8zD5xH1pCh7FztZS86JqUGmGWR8jEiHMBpCe3EKUSUrGP6A!/b&bo=QAIpAkACKQIRECc!&rf=viewer_311");
        list.add("http://a1.qpic.cn/psc?/V54eSsR74GmfBT42pSAT26RsMd0ZtmmF/bqQfVz5yrrGYSXMvKr.cqW8091wt*C11YoJu9T0MRA6fTEOV7SwOtBNKGCtdpyZTOSOZDAMjx8sAY5RvOpP6yxLHoA2hGQAkPnZsHpPBZ5A!/b&ek=1&kp=1&pt=0&bo=1ALXAtQC1wIDEDU!&tl=1&vuin=972381686&tm=1639357200&sce=60-4-3&rf=viewer_311");
        TiaoSaoListAdapter adapter = new TiaoSaoListAdapter(R.layout.item_ts_list, list);
        View head = LayoutInflater.from(getActivity()).inflate(R.layout.layout_head_view, null);
        TextView tv_head = head.findViewById(R.id.tv_head);
        tv_head.setText("热门活动");
        adapter.setHeaderView(head);
        recyTiaosao.setAdapter(adapter);
    }


    private void initList() {
        list.clear();
        list = DataSupport.findAll(GoodsBean.class);
        Collections.reverse(list);
        adapter = new GoodsListAdapter(R.layout.item_goods_list_gv, list);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_list_empty, null);
        TextView tv_empty = view.findViewById(R.id.tv_empty_title);
        tv_empty.setText("暂无商品，等待用户发布");
        adapter.setEmptyView(view);
        recy.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        recy.setAdapter(adapter);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", list.get(position));
                skipActivity(getActivity(), GoodsDetailActivity.class, bundle);
            }
        });

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                del(position);
            }
        });
    }


    private void del(int position) {

        customDialog = DialogUtil.showDialog(getActivity(), customDialog, 2, dialog_title, dialog_content, "取消", "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                DataSupport.deleteAll(GoodsBean.class, "goods_id=?", list.get(position).getGoods_id());
                list.remove(position);
                adapter.notifyDataSetChanged();
                ToastUtil.showToast(getActivity(), "删除成功");
            }
        });

        if (customDialog != null && !customDialog.isShowing()) {
            customDialog.show();
        }


        customDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                customDialog = null;
            }
        });

    }


    @Override
    public void onEvent(EventMessage msg) {
        super.onEvent(msg);
        if (msg.getMessageType() == EventMessage.REFRESH) {
            initList();
        }
    }



    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_search:
                skipActivity(getActivity(), SearchActivity.class);
                break;
        }
    }


    /**
     * 轮播图
     */
    private void initBanner() {
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new FresscoImageLoader());
        //设置banner动画效果
//        banner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置允许手势滑动
        banner.setViewPagerIsScroll(true);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);

        List list_banner = new ArrayList();
        list_banner.add("https://img2.baidu.com/it/u=2212354885,982694596&fm=26&fmt=auto");
        list_banner.add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Fback_pic%2F05%2F57%2F13%2F145b2337dc16b60.jpg%21r850%2Ffw%2F800&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640441025&t=1fadce4a2cb25251db19828f114f3576");
        banner.setImages(list_banner);

        //banner设置方法全部调用完毕时最后调用
        banner.start();

        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

            }
        });
    }


    public class FresscoImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            String url = (String) path;
            GlideUtils.getInstance().loadImage(getActivity(), url, imageView);
        }

        //提供createImageView 方法，方便fresco自定义ImageView
        @Override
        public ImageView createImageView(Context context) {

            ImageView simpleDraweeView = (ImageView) getLayoutInflater().inflate(R.layout.layout_banner_imageview, null);
//            SimpleDraweeView simpleDraweeView = new SimpleDraweeView(context);
            return simpleDraweeView;
        }
    }

}
